package com.totem.base.util;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */

import java.sql.Timestamp;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 多线程并发获取时间戳时,System.currentTimeMillis有可能比这个更好
 * 仅学习用,不上生产
 */
public class SystemClock {
    // 更新当前时间的间隔,毫秒
    private final long period;
    // 当前时间,毫秒
    private volatile long now;

    public SystemClock(long period){
        this.period = period;
        this.now = System.currentTimeMillis();
    }

    public void scheduleUpdateClock(){
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, (r)->{
            Thread t = new Thread(r, "System Clock");
            t.setDaemon(true);
            return t;
        });
        scheduler.scheduleAtFixedRate(()->now=System.currentTimeMillis(), period, period, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis(){
        return now;
    }

    private static class InstanceHolder {
        public static final SystemClock INSTANCE = new SystemClock(1);
    }

    public static long now(){
        return InstanceHolder.INSTANCE.currentTimeMillis();
    }

    public static String nowTime(){
        return new Timestamp(InstanceHolder.INSTANCE.currentTimeMillis()).toString();
    }
}
